'use client'

import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Upload, Image as ImageIcon, Zap, X, Plus } from 'lucide-react'
import Image from "next/image"

// 模拟API调用
const generateThumbnails = async () => {
  await new Promise(resolve => setTimeout(resolve, 2000))
  return Array(5).fill(null).map((_, i) => `/placeholder.svg?text=Thumbnail ${i + 1}`)
}

const generateHighRes = async () => {
  await new Promise(resolve => setTimeout(resolve, 3000))
  return '/placeholder.svg?text=High Resolution'
}

export default function OptimizedMobilePhotoEnhancer() {
  const [uploadedPhotos, setUploadedPhotos] = useState([])
  const [thumbnails, setThumbnails] = useState([])
  const [selectedThumbnails, setSelectedThumbnails] = useState(new Set())
  const [highResPhoto, setHighResPhoto] = useState(null)
  const [credits, setCredits] = useState(100)
  const [isGenerating, setIsGenerating] = useState(false)
  const [isGeneratingHighRes, setIsGeneratingHighRes] = useState(false)

  const handlePhotoUpload = (event) => {
    const files = event.target.files
    if (files) {
      const newPhotos = Array.from(files).map(file => URL.createObjectURL(file))
      setUploadedPhotos(prev => [...prev, ...newPhotos].slice(0, 2))
    }
  }

  const handleRemovePhoto = (index) => {
    setUploadedPhotos(prev => prev.filter((_, i) => i !== index))
  }

  const handleGenerateThumbnails = async () => {
    if (uploadedPhotos.length !== 2) {
      alert('请上传2张照片')
      return
    }
    setIsGenerating(true)
    try {
      const newThumbnails = await generateThumbnails()
      setThumbnails(prev => [...prev, ...newThumbnails])
      setCredits(prev => prev - 5)
    } catch (error) {
      console.error('生成缩略图失败:', error)
    } finally {
      setIsGenerating(false)
    }
  }

  const handleThumbnailSelect = (index) => {
    setSelectedThumbnails(prev => {
      const newSet = new Set(prev)
      if (newSet.has(index)) {
        newSet.delete(index)
      } else {
        newSet.add(index)
      }
      return newSet
    })
  }

  const handleGenerateHighRes = async () => {
    if (selectedThumbnails.size === 0) {
      alert('请至少选择一张缩略图')
      return
    }
    setIsGeneratingHighRes(true)
    try {
      const highResUrl = await generateHighRes()
      setHighResPhoto(highResUrl)
      setCredits(prev => prev - 10)
    } catch (error) {
      console.error('生成高清图片失败:', error)
    } finally {
      setIsGeneratingHighRes(false)
    }
  }

  return (
    <div className="max-w-md mx-auto p-4 space-y-6">
      <section className="space-y-4">
        <Label htmlFor="photo-upload" className="block">上传照片 (需要2张)</Label>
        <div className="flex items-center gap-2">
          <Button asChild className="w-full">
            <Label htmlFor="photo-upload" className="cursor-pointer">
              <Upload className="w-4 h-4 mr-2" />
              选择照片
              <span>{uploadedPhotos.length}/2</span>
            </Label>
          </Button>
          <Input id="photo-upload" type="file" accept="image/*" multiple onChange={handlePhotoUpload} className="hidden" />

        </div>
      </section>

      {uploadedPhotos.length > 0 && (
        <section className="space-y-2">
          <h2 className="text-lg font-semibold">已上传的照片</h2>
          <div className="grid grid-cols-4 gap-4">
            {uploadedPhotos.map((photo, index) => (
              <div key={index} className="relative">
                <Image src={photo} alt={`已上传 ${index + 1}`} width={100} height={100} className="w-full h-24 object-cover rounded" />
                <Button
                  size="icon"
                  variant="destructive"
                  className="absolute top-1 right-1"
                  onClick={() => handleRemovePhoto(index)}
                >
                  <X className="w-4 h-4" />
                  <span className="sr-only">删除照片</span>
                </Button>
              </div>
            ))}
          </div>
        </section>
      )}

      <Button onClick={handleGenerateThumbnails} disabled={uploadedPhotos.length !== 2 || isGenerating} className="w-full">
        {isGenerating ? '正在生成...' : '生成缩略图'}
      </Button>

      {thumbnails.length > 0 && (
        <section className="space-y-2">
          <h2 className="text-lg font-semibold">缩略图</h2>
          <ScrollArea className="h-48 w-full rounded-md border">
            <div className="grid grid-cols-3 gap-2 p-2">
              {thumbnails.map((thumbnail, index) => (
                <div key={index} className="relative">
                  <Image src={thumbnail} alt={`缩略图 ${index + 1}`} width={100} height={100} className="w-full h-24 object-cover rounded" />
                  <Checkbox
                    id={`thumbnail-${index}`}
                    checked={selectedThumbnails.has(index)}
                    onCheckedChange={() => handleThumbnailSelect(index)}
                    className="absolute top-1 right-1"
                  />
                </div>
              ))}
              <Button variant="outline" className="h-24 flex flex-col items-center justify-center" onClick={handleGenerateThumbnails}>
                <Plus className="w-6 h-6 mb-1" />
                生成更多
              </Button>
            </div>
          </ScrollArea>
        </section>
      )}

      {selectedThumbnails.size > 0 && (
        <Button onClick={handleGenerateHighRes} className="w-full" disabled={isGeneratingHighRes}>
          {isGeneratingHighRes ? '正在生成高清图...' : '获取高清图'}
        </Button>
      )}

      {highResPhoto && (
        <section className="space-y-2">
          <h2 className="text-lg font-semibold">高清图片</h2>
          <Card>
            <CardContent className="p-4">
              <Image src={highResPhoto} alt="高清图片" width={100} height={100} className="w-full rounded" />
              <p className="text-center mt-2 text-green-600">高清图片已生成！点击保存。</p>
            </CardContent>
          </Card>
        </section>
      )}
    </div>
  )
}